package com.ruoyi.recycle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.recycle.domain.*;
import com.ruoyi.recycle.dto.ClientCollectionCommodityDTO;
import com.ruoyi.recycle.dto.IntegralCommodityDTO;
import com.ruoyi.recycle.dto.IntegralCommodityVO;
import com.ruoyi.recycle.mapper.*;
import com.ruoyi.recycle.service.IIntegralCommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 积分商品Service业务层处理
 *
 * @author Wubk
 * @date 2022-05-22
 */
@Service
public class IntegralCommodityServiceImpl extends ServiceImpl<IntegralCommodityMapper, IntegralCommodity> implements IIntegralCommodityService {
    @Autowired
    private IntegralCommodityMapper integralCommodityMapper;
    @Resource
    private IntegralCommoditySizeMapper integralCommoditySizeMapper;
    @Resource
    private IntegralCommodityEvaluateMapper integralCommodityEvaluateMapper;
    @Resource
    private ClientCollectionCommodityMapper clientCollectionCommodityMapper;
    @Resource
    private IntegralOrderMapper integralOrderMapper;
    @Resource
    private CommoditySizeConfigMapper commoditySizeConfigMapper;
    @Resource
    private CommodityRepertoryMapper commodityRepertoryMapper;
    @Resource
    private AdminAddressMapper adminAddressMapper;

    /**
     * 查询积分商品
     *
     * @param id 积分商品主键
     * @return 积分商品
     */
    @Override
    public AjaxResult selectIntegralCommodityById(Long id) {

        IntegralCommodity integralCommodity = integralCommodityMapper.selectIntegralCommodityById(id);
        //尺码库存
        LambdaQueryWrapper<CommoditySizeConfig> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CommoditySizeConfig::getCommodityId, id);
        wrapper.eq(CommoditySizeConfig::getSizeType, "1");
        List<CommoditySizeConfig> typeConfigList = commoditySizeConfigMapper.selectList(wrapper);

        LambdaQueryWrapper<CommoditySizeConfig> sizeWrapper = Wrappers.lambdaQuery();
        sizeWrapper.eq(CommoditySizeConfig::getCommodityId, id);
        sizeWrapper.eq(CommoditySizeConfig::getSizeType, "2");
        List<CommoditySizeConfig> sizeConfigList = commoditySizeConfigMapper.selectList(sizeWrapper);


        return AjaxResult.success(integralCommodity).put("typeConfigList",typeConfigList).put("sizeConfigList",sizeConfigList);
    }

    /**
     * 查询积分商品列表
     *
     * @param integralCommodity 积分商品
     * @return 积分商品
     */
    @Override
    public List<IntegralCommodity> selectIntegralCommodityList(IntegralCommodity integralCommodity) {
        return integralCommodityMapper.selectIntegralCommodityList(integralCommodity);
    }

    /**
     * 新增积分商品
     *
     * @param integralCommodity 积分商品
     * @return 结果
     */
    @Override
    public int insertIntegralCommodity(IntegralCommodityVO integralCommodity) {

        String username = SecurityUtils.getUsername();

        IntegralCommodity commodity = new IntegralCommodity();
        BeanUtils.copyProperties(integralCommodity,commodity);
        int i = integralCommodityMapper.insert(commodity);

        List<CommoditySizeConfig> commoditySizeConfigList = integralCommodity.getCommoditySizeConfigList();
        if (commoditySizeConfigList.size()>0){
            for (CommoditySizeConfig commoditySizeConfig : commoditySizeConfigList) {
                commoditySizeConfig.setCreatedBy(username);
                commoditySizeConfig.setCreatedTime(new Date());
                commoditySizeConfig.setCommodityId(Math.toIntExact(commodity.getId()));
                commoditySizeConfigMapper.insert(commoditySizeConfig);
            }
        }


        return i;
    }

    /**
     * 修改积分商品
     *
     * @param integralCommodity 积分商品
     * @return 结果
     */
    @Override
    public int updateIntegralCommodity(IntegralCommodityVO integralCommodity) {

        List<Long> deleteSizeList = integralCommodity.getDeleteSizeList();
        if (deleteSizeList.size()>0){
            commoditySizeConfigMapper.deleteBatchIds(deleteSizeList);
        }

        List<CommoditySizeConfig> commoditySizeConfigList = integralCommodity.getCommoditySizeConfigList();
        if (commoditySizeConfigList.size()>0){
            for (CommoditySizeConfig commoditySizeConfig : commoditySizeConfigList) {
                if (StringUtils.isNull(commoditySizeConfig.getId()) || commoditySizeConfig.getId() == 0){
                    commoditySizeConfig.setCommodityId(Math.toIntExact(integralCommodity.getId()));
                    commoditySizeConfigMapper.insert(commoditySizeConfig);
                }
            }
        }
        IntegralCommodity commodity = new IntegralCommodity();
        BeanUtils.copyProperties(integralCommodity,commodity);
        return integralCommodityMapper.updateIntegralCommodity(commodity);
    }

    /**
     * 批量删除积分商品
     *
     * @param ids 需要删除的积分商品主键
     * @return 结果
     */
    @Override
    public int deleteIntegralCommodityByIds(Long[] ids) {
        //库存尺寸同步删除
        for (Long id : ids) {
            //库存尺寸
            LambdaQueryWrapper<IntegralCommoditySize> commodityWrapper = Wrappers.lambdaQuery();
            commodityWrapper.eq(IntegralCommoditySize::getCommodityId, id);
            integralCommoditySizeMapper.delete(commodityWrapper);
            //规格 尺寸
            LambdaQueryWrapper<CommoditySizeConfig> sizeWrapper = Wrappers.lambdaQuery();
            sizeWrapper.eq(CommoditySizeConfig::getCommodityId, id);
            commoditySizeConfigMapper.delete(sizeWrapper);
        }
        return integralCommodityMapper.deleteIntegralCommodityByIds(ids);
    }

    /**
     * 删除积分商品信息
     *
     * @param id 积分商品主键
     * @return 结果
     */
    @Override
    public int deleteIntegralCommodityById(Long id) {

        LambdaQueryWrapper<IntegralCommoditySize> commodityWrapper = Wrappers.lambdaQuery();
        commodityWrapper.eq(IntegralCommoditySize::getCommodityId, id);
        integralCommoditySizeMapper.delete(commodityWrapper);
        //规格 尺寸
        LambdaQueryWrapper<CommoditySizeConfig> sizeWrapper = Wrappers.lambdaQuery();
        sizeWrapper.eq(CommoditySizeConfig::getCommodityId, id);
        commoditySizeConfigMapper.delete(sizeWrapper);
        return integralCommodityMapper.deleteIntegralCommodityById(id);
    }

    /**
     * 商品内容详情页
     *
     * @return
     */
    @Override
    public AjaxResult selectAllIntegralCommodity(Integer id) {

        IntegralCommodity integralCommodity = integralCommodityMapper.selectById(id);

        IntegralCommodityDTO integralCommodityDTO = new IntegralCommodityDTO();
        BeanUtils.copyProperties(integralCommodity, integralCommodityDTO);

        //尺码库存
        LambdaQueryWrapper<IntegralCommoditySize> sizeQueryWrapper = Wrappers.lambdaQuery();
        sizeQueryWrapper.eq(IntegralCommoditySize::getCommodityId, id);
        List<IntegralCommoditySize> integralCommoditySizeList = integralCommoditySizeMapper.selectList(sizeQueryWrapper);

        integralCommodityDTO.setIntegralCommoditySizeList(integralCommoditySizeList);
        //评价详情
        LambdaQueryWrapper<IntegralCommodityEvaluate> evaluateQueryWrapper = Wrappers.lambdaQuery();
        evaluateQueryWrapper.eq(IntegralCommodityEvaluate::getCommodityId, id);
        List<IntegralCommodityEvaluate> integralCommodityEvaluateList = integralCommodityEvaluateMapper.selectList(evaluateQueryWrapper);

        integralCommodityDTO.setIntegralCommodityEvaluateList(integralCommodityEvaluateList);

        //月销量
        Long salesVolume = integralOrderMapper.getCommoditySalesVolume(id);

        //收藏排行
        int collectionCommodity = 0;
        List<ClientCollectionCommodityDTO> clientCollectionCommodityDTOList = clientCollectionCommodityMapper.orderByCollectionDesc(id);
        for (int i = 0; i < clientCollectionCommodityDTOList.size(); i++) {
            collectionCommodity = i+1;
            if(clientCollectionCommodityDTOList.get(i).getCommodityId() !=null && clientCollectionCommodityDTOList.get(i).getCommodityId() == id) {
                break;
            }
        }

        List<AdminAddress> sendAddress = adminAddressMapper.selectList(new LambdaQueryWrapper<>());
        AdminAddress adminAddress = new AdminAddress();
        if (sendAddress.size() > 0) {
             adminAddress = sendAddress.get(0);
        }
        return AjaxResult.success(integralCommodityDTO).put("salesVolume",salesVolume).put("collectionCommodity",collectionCommodity).put("sendAddress",adminAddress);
    }

    /**
     * 客户收藏商品
     * @param clientId
     * @return
     */
    @Override
    public AjaxResult collect(Integer clientId, Integer collectId,Integer type) {
        ClientCollectionCommodity clientCollectionCommodity = new ClientCollectionCommodity();
        clientCollectionCommodity.setClientId(clientId);
        LambdaQueryWrapper<ClientCollectionCommodity> queryWrapper = Wrappers.lambdaQuery();

        if (type == 0){
            clientCollectionCommodity.setCommodityId(collectId);
            queryWrapper.eq(ClientCollectionCommodity::getCommodityId, collectId);
            queryWrapper.eq(ClientCollectionCommodity::getClientId, clientId);
            List<ClientCollectionCommodity> collectionCommodityList = clientCollectionCommodityMapper.selectList(queryWrapper);
            if (collectionCommodityList.size()>0){
                return AjaxResult.success("已收藏");
            }
        }else {
            clientCollectionCommodity.setShopId(collectId);
            queryWrapper.eq(ClientCollectionCommodity::getShopId, collectId);
            queryWrapper.eq(ClientCollectionCommodity::getClientId, clientId);
            List<ClientCollectionCommodity> collectionCommodityList = clientCollectionCommodityMapper.selectList(queryWrapper);
            if (collectionCommodityList.size()>0){
                return AjaxResult.success("已收藏");
            }
        }
        clientCollectionCommodity.setCreatedBy("admin");
        clientCollectionCommodity.setCreatedTime(new Date());

        clientCollectionCommodityMapper.insert(clientCollectionCommodity);
        return AjaxResult.success("添加成功");
    }


    @Override
    public AjaxResult cancelCollect(Integer clientId, Integer collectId,Integer type) {
        ClientCollectionCommodity clientCollectionCommodity = new ClientCollectionCommodity();
        clientCollectionCommodity.setClientId(clientId);
        if (type == 0) {
            clientCollectionCommodity.setCommodityId(collectId);
        }else {
            clientCollectionCommodity.setShopId(collectId);
        }
        QueryWrapper<ClientCollectionCommodity> queryWrapper = new QueryWrapper<>(clientCollectionCommodity);

        clientCollectionCommodityMapper.delete(queryWrapper);
        return AjaxResult.success("删除成功");
    }

    @Override
    public AjaxResult insertCommoditySizeConfig(CommoditySizeConfig commoditySizeConfig) {
        commoditySizeConfigMapper.insert(commoditySizeConfig);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deleteCommoditySizeConfig(CommoditySizeConfig commoditySizeConfig) {
        commoditySizeConfigMapper.delete(new QueryWrapper<>(commoditySizeConfig));
        return AjaxResult.success();
    }

    @Override
    public AjaxResult selectCommoditySizeConfig(Integer commodityId) {
        LambdaQueryWrapper<CommoditySizeConfig> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CommoditySizeConfig::getCommodityId, commodityId);
        List<CommoditySizeConfig> commoditySizeConfigs = commoditySizeConfigMapper.selectList(queryWrapper);
        return AjaxResult.success(commoditySizeConfigs);
    }

    @Override
    public AjaxResult addCommodityRepertory(List<CommodityRepertory> commodityRepertoryList) {

        for (CommodityRepertory commodityRepertory : commodityRepertoryList) {
            if (StringUtils.isNull(commodityRepertory.getId()) || commodityRepertory.getId() == 0){
                //采购
                List<IntegralCommoditySize> integralCommoditySizeList = getIntegralCommoditySizeList(commodityRepertory);

                if ("1".equals(commodityRepertory.getRepertoryType())) {

                    if (integralCommoditySizeList.size() > 0) {
                        //存在则说明是已存在尺寸，操作库存，不存在则说明是新增的尺寸库存，插入一条积分商品库存信息
                        IntegralCommoditySize integralCommoditySize = integralCommoditySizeList.get(0);
                        integralCommoditySize.setInventory(integralCommoditySize.getInventory() + commodityRepertory.getQuantity());
                        integralCommoditySizeMapper.updateIntegralCommoditySize(integralCommoditySize);
                    } else {
                        IntegralCommoditySize integralCommoditySize = new IntegralCommoditySize();
                        integralCommoditySize.setCommodityId(Long.valueOf(commodityRepertory.getCommodityId()));
                        integralCommoditySize.setSize(commodityRepertory.getCommoditySize());
                        integralCommoditySize.setSpecification(commodityRepertory.getCommodityType());
                        integralCommoditySize.setCreatedBy(commodityRepertory.getCreatedBy());
                        integralCommoditySize.setCreatedTime(new Date());
                        integralCommoditySize.setName(commodityRepertory.getCommoditySize());
                        integralCommoditySize.setInventory(Long.valueOf(commodityRepertory.getQuantity()));
                        integralCommoditySizeMapper.insert(integralCommoditySize);
                    }
                } else if ("2".equals(commodityRepertory.getRepertoryType())) {

                    //退货
                    if (integralCommoditySizeList.size() > 0) {
                        //存在则说明是已存在尺寸，操作库存
                        IntegralCommoditySize integralCommoditySize = integralCommoditySizeList.get(0);
                        if (commodityRepertory.getQuantity() > integralCommoditySize.getInventory()) {
                            return AjaxResult.error("退货无法大于当前库存数，无法退货，请核对库存数据");
                        } else {
                            integralCommoditySize.setInventory(integralCommoditySize.getInventory() - commodityRepertory.getQuantity());
                            integralCommoditySizeMapper.updateIntegralCommoditySize(integralCommoditySize);
                        }
                    } else {
                        return AjaxResult.error("未存在对应尺寸的库存记录，无法退货，请先采购对应的库存数据");
                    }
                }
                //插入记录
                commodityRepertoryMapper.insert(commodityRepertory);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 获取积分商品采购与退货库存记录
     */
    @Override
    public AjaxResult getCommodityRepertory(CommodityRepertory commodityRepertory) {
        LambdaQueryWrapper<CommodityRepertory> commodityRepertoryLambdaQueryWrapper = Wrappers.lambdaQuery();
        commodityRepertoryLambdaQueryWrapper.eq(CommodityRepertory::getCommodityId, commodityRepertory.getCommodityId());
        commodityRepertoryLambdaQueryWrapper.eq(CommodityRepertory::getRepertoryType, commodityRepertory.getRepertoryType());
        List<CommodityRepertory> commodityRepertoryList = commodityRepertoryMapper.selectList(commodityRepertoryLambdaQueryWrapper);
        return AjaxResult.success(commodityRepertoryList);
    }


    @Override
    public AjaxResult collectCommodityPageQuery(Long clientId, Integer currentPage, Integer pageSize) {
        List<IntegralCommodity> integralCommodityList = integralCommodityMapper.collectCommodityPageQuery(clientId);
        List<IntegralCommodity> subList = integralCommodityList.stream().skip((currentPage-1)*pageSize).limit(pageSize).collect(Collectors.toList());
        return AjaxResult.success(subList).put("currentPage",currentPage).put("pageSize",pageSize).put("total",integralCommodityList.size());
    }

    private List<IntegralCommoditySize> getIntegralCommoditySizeList(CommodityRepertory commodityRepertory) {

        LambdaQueryWrapper<IntegralCommoditySize> commoditySizeQueryWrapper = Wrappers.lambdaQuery();
        commoditySizeQueryWrapper.eq(IntegralCommoditySize::getCommodityId, commodityRepertory.getCommodityId());
        commoditySizeQueryWrapper.eq(IntegralCommoditySize::getSpecification, commodityRepertory.getCommodityType());
        commoditySizeQueryWrapper.eq(IntegralCommoditySize::getSize, commodityRepertory.getCommoditySize());
        List<IntegralCommoditySize> integralCommoditySizeList = integralCommoditySizeMapper.selectList(commoditySizeQueryWrapper);
        return integralCommoditySizeList;
    }


}
